<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/5/2 0002
 * Time: 09:22
 */
namespace app\admin\controller\system;
use app\admin\model\publicuse\PublicUse;
use app\admin\model\SystemField;
use app\admin\model\traits\TablHandle;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\Exception;
use think\facade\Db;
/**
 * @ControllerAnnotation(title="字段管理")
 * Class Fields
 * @package app\admin\controller\system
 */
class Fields extends AdminController
{
    use \app\admin\traits\Curd;
    protected $allowModifyFields = [
        'show',
        'edit',
        'search',
        'total',
        'export',
        'status',
        'is_key',
    ];
    protected $sort = [
        'sort' => 'desc',
        'id'   => 'asc',
    ];
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new SystemField();
        $array = PublicUse::getConfigDir(__CLASS__);
//        echo __DIR__.DS.'field'.DS.$array['class'].'.txt';exit;
        if(is_file(__DIR__.DIRECTORY_SEPARATOR.'field'.DIRECTORY_SEPARATOR.$array['class'].'.json')){
            $this->AllData = json_decode(file_get_contents(__DIR__.DIRECTORY_SEPARATOR.'field'.DIRECTORY_SEPARATOR.$array['class'].'.json'),true);
        }
    }

    public function index()
    {
        $id = request()->param('id',null);
        $field = request()->param('field',null);
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $where = PublicUse::getParameter($where);
//            dump($where);exit;
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select()->toArray();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $parameter = '';
        if(!empty($id)&&!empty($field)){
            $model = Db::name('system_model')
                ->where('id',$id)
                ->findOrEmpty();
            $id = $model['table'];
            $parameter = "?$field=$id";
        }
        $this->assign('parameter',$parameter);
        return $this->fetch();
    }
    public function add()
    {
        $data = request()->param();
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            if(isset($this->AllData['field'])&&!empty($this->AllData['field'])){
                $post = PublicUse::Conversion($post,$this->AllData['field']);
            }
            if(isset($post['is_key'])&&$post['is_key']=='on'){
                $post['is_key'] = 1;
            }else{
                $post['is_key'] = 0;
            }
//            return $this->error('创建字段失败',202,$post);
            $bool = TablHandle::AddField($post);
            if(!$bool){
                return $this->error('创建字段失败');
            }
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
//        echo '<pre>';
//        print_r($this->AllData);
//        exit;
        $this->assign('alldata',$this->AllData);
        $this->assign('row',$data);
        $this->assign('getTableList',$this->model->getTableList());
        return $this->fetch();
    }
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
//            return $this->error('创建字段失败',$post);
            if(isset($this->AllData['field'])&&!empty($this->AllData['field'])){
                $post = PublicUse::Conversion($post,$this->AllData['field']);
            }
            if(isset($post['is_key'])&&$post['is_key']=='on'){
                $post['is_key'] = 1;
            }else{
                $post['is_key'] = 0;
            }
            $bool = TablHandle::UpdateField($row->toArray(),$post);
//            dump($post);die();
//            return $this->error($bool,202);
            if(!$bool){
                return $this->error('修改字段失败');
            }
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
//                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        $this->assign('alldata',$this->AllData);
        $this->assign('getTableList',$this->model->getTableList());
        return $this->fetch();
    }
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        $bool = TablHandle::DeleteField($row->toArray());
        if(!$bool){
            return $this->error('删除字段失败');
        }
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }
}